#!/bin/bash
#监控指定进程的CPU利用率，内存变化率; 
#通过解析/proc/<pid>/stat文件来实现

#错误退出代码;
EXIT_PIDNUM=2;
EXIT_PROCESS_NON_EXIT=3;

#监控所有的进程函数； 

monitor_all_process(){

	#获取目录中所有进程号
	file_process=`find /proc -maxdepth 1 -name "[0-9]*"`;
	printf "%s %12s %15s %12s %15s\n" "进程号" "CPU" "VMZ" "MEM" "进程名"
	count=0; 
	for pid_with_path in $file_process
	do
		pid_cur=${pid_with_path##*/}
		if [ -e $pid_with_path/stat ];
		then
			cat $pid_with_path/stat | awk -F " " \
			'{count=count+1;consumer=$14+$15+$16+$17;\
			printf "%s %15s %15s %15s %15s\n",$1,consumer,$23,$24,$2}'
			count=$(( $count + 1 ))
		fi
	done
	printf "您一共启动了%s个进程\n" $count
}

#判断进程号所代表的进程是否存在；
judge_pid_exist(){
	file_process=`find /proc -maxdepth 1 -name "[0-9]*"`;
	for pid_with_path in $file_process
	do
		pid_cur=${pid_with_path##*/}
		if [[ "$pid_cur" = $1 ]];
		then
			return 0
		fi
	done
	return $EXIT_PROCESS_NON_EXIT;
}

#监控某一个进程; 
monitor_process_pid(){
	if find /proc -maxdepth 1 -name "$PID_NUM" &>/dev/null
	then
		printf "%s %12s %15s %12s %15s\n" "进程号" "CPU" "VMZ" "MEM" "进程名"
    cat "/proc/""$PID_NUM""/stat" | awk -F " " \
	  '{count=count+1;consumer=$14+$15+$16+$17;\
    printf "%s %15s %15s %15s %15s\n",$1,consumer,$23,$24,$2}'
	fi
	
}
#统计当前总共进程数和最大的进程号； 
temp=`ps aux | awk -F " " 'BEGIN{count=0}{if(NR!=1) count=count+1}END{print count " " $2}'`

MAX_COUNT_CUR=`echo $temp | cut -d ' ' -f 1`
MAX_PID_NUM_CUR=`echo $temp | cut -d ' ' -f 2`

echo "请您输入需要监控的进程号，输入0监控所有的进程，如果需要监控指定的进程请您输入1-$MAX_PID_NUM_CUR之间的数字:"
read PID_NUM

#使用if语句进行判断; 
if [[ "$PID_NUM" == [!0-9]* ]];
then
	echo "您输入的进程号不是数字，请您重新进行输入"
	exit $EXIT_PIDNUM;
elif [[ $PID_NUM == 0 ]];
then
	echo "您需要对所有的进程进行监控"; 
	monitor_all_process;
elif [[ "$PID_NUM" < 0 ]] || [[ "$PID_NUM" -ge "$MAX_PID_NUM_CUR" ]] || ! judge_pid_exist $PID_NUM;
then
	echo "您输入的进程号无效，请重新输入在0-$MAX_PID_NUM_CUR之间的进程号"
	exit $EXIT_PIDNUM; 
else
	echo "您需要对进程号$PID_NUM进行监控"
	judge_pid_exist $PID_NUM; 
	monitor_process_pid $PID_NUM
fi
	

#判断数据的内容是否正确，并且根据输入的内容进行实际的操作; 
#case $PID_NUM in
#	[!0-9]* )
#		echo "您输入的进程号不是数字，请您重新进行输入"
#		exit $EXIT_PIDNUM;
#		;;
#	#[ "$PID_NUM" -lt "0" ] \
#	# || [ "$PID_NUM" -gt "$MAX_PID_NUM_CUR" ] )
#	"q" )
#echo "您输入的进程号无效，请您输入在0-$MAX_PID_NUM_CUR之间的进程号"
#		exit $EXIT_PIDNUM; 
#		;; 
#	0)
#		echo "您需要对所有的进程进行监控"; 
#		#monitor_all_process;
#		;;
#	*)
#		echo "您需要对进程号:"$PID_NUM"进行监控"
		#judge_pid_exist $PID_NUM; 
		#monitor_process_pid $PID_NUM
#		;;
#esac
	
